//
//  UIColor+Extension.swift
//  CommonKit
//
//  Created by guohq on 2021/7/7.
//

import UIKit


@objc public extension UIColor{
    
    /// 颜色
    ///
    /// - Parameters:
    ///   - r: 红色值
    ///   - g: 绿色值
    ///   - b: 蓝色值
    /// - Returns: 颜色
    @objc static func kRGB(r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor {
        return kRGBA(r: r, g: g, b: b, a: 1)
    }
    
    /// 颜色
    ///
    /// - Parameters:
    ///   - r: 红色值
    ///   - g: 绿色值
    ///   - b: 蓝色值
    ///   - a: 透明度
    /// - Retuurns: 颜色
    @objc static func kRGBA(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> UIColor {
        return UIColor(red: r/255, green: g/255, blue: b/255, alpha: a)
    }
    
    /**
     16进制转UIColor

     - parameter hex: 16进制

     - returns: UIColor
     */
    @objc static func colorWithHexString(_ hex:String) -> UIColor {
        return colorWithHexString(hex, alpha: 1.0)
    }

    /// 16进制转UIColor
    /// - Parameter hex: 16进制
    /// - Parameter alpha: 透明度
    @objc static func colorWithHexString(_ hex: String, alpha: CGFloat) -> UIColor {
        var cString:String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).uppercased()

        if (cString.hasPrefix("#")) {
            cString = (cString as NSString).substring(from: 1)
        }

        if (cString.count != 6) {
            return UIColor.gray
        }

        let rString = (cString as NSString).substring(to: 2)
        let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
        let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)

        var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0
        Scanner(string: rString).scanHexInt32(&r)
        Scanner(string: gString).scanHexInt32(&g)
        Scanner(string: bString).scanHexInt32(&b)

        return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha)
    }
}
